package com.ailk.tcm.hffw.android.common.ui;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

import com.ailk.tcm.R;
import com.ailk.tcm.hffw.android.common.MyApplication;

public class ImageSelectDialog extends DialogFragment implements OnClickListener{
	
	public static final int REQUEST_IMAGE = 0;
	public static final int REQUEST_CAMERA = 1;
	
	private OnImageSelectedListener imageSelectedListener;
	private Uri cameraImageUri;
	private Mode mode = Mode.CAMERA_AND_PHOTO;

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		final CharSequence[] items = { getResources().getString(R.string.album), 
				getResources().getString(R.string.photo) };
		Activity a = getActivity();
		Dialog d = null;
		if(mode == Mode.CAMERA_AND_PHOTO){
			d = new Dialog(a);
			LinearLayout l = new LinearLayout(a);
			l.setGravity(Gravity.CENTER);
			l.setOrientation(LinearLayout.HORIZONTAL);
			l.setPadding(5, 5, 5, 5);
			l.setMinimumHeight(150);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
			lp.weight = 1;
			Button b0 = new Button(a);
			b0.setText(items[0]);
			b0.setTag(0);
			b0.setOnClickListener(this);
			b0.setPadding(5, 5, 5, 5);
			l.addView(b0, lp);
			Button b1 = new Button(a);
			b1.setText(items[1]);
			b1.setTag(1);
			b1.setOnClickListener(this);
			b1.setPadding(5, 5, 5, 5);
			l.addView(b1, lp);
			d.setContentView(l);
			d.setTitle(R.string.select_image);
		}else {
			d = new Dialog(a, R.style.Dialog_Translucent_NoTitle);
			WindowManager.LayoutParams dlp = d.getWindow().getAttributes();
			dlp.width = 0;
			dlp.height = 0;
			d.getWindow().setAttributes(dlp);
		}
		if(mode == Mode.PHOTO){
			gotoPhoto();
		}else if(mode == Mode.CAMERA){
			gotoCamera();
		}
		return d;
	}
	
	@Override
	public void onClick(View v) {
		if ((Integer)v.getTag() == 0){
			gotoPhoto();
        } else{
        	gotoCamera();
        }
	}
	
	private void gotoPhoto(){
		Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
        getImage.addCategory(Intent.CATEGORY_OPENABLE);
        getImage.setType("image/*");
        startActivityForResult(getImage, REQUEST_IMAGE);
	}
	
	private void gotoCamera(){
		Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
    	File fTempIamge = new File(MyApplication.DOWNLOAD_IMAGES_STORE_PATH, "1.jpg");
    	if(fTempIamge.exists()){
    		fTempIamge.delete();
    	}
    	cameraImageUri = Uri.fromFile(fTempIamge);
    	getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
        startActivityForResult(getImageByCamera, REQUEST_CAMERA);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		this.dismiss();
		ContentResolver contentResolver = getActivity().getContentResolver();
		ImagePackage imagePackage = new ImagePackage();
		imagePackage.type = requestCode;
		if (requestCode == REQUEST_IMAGE){
            try{
                // 获得图片的uri
                Uri originalUri = data.getData();
                imagePackage.uri = originalUri;
                //将图片内容解析成字节数组
                imagePackage.byteArray = readStream(contentResolver.openInputStream(Uri.parse(originalUri.toString())));
                imagePackage.status = true;
            } catch (Exception e){
            	e.printStackTrace();
            }
        }else if(requestCode == REQUEST_CAMERA){
            try{
                super.onActivityResult(requestCode, resultCode, data);
                /*Bundle extras = data.getExtras();
                if(extras.get("data") != null){
                	imagePackage.bitmap = (Bitmap) extras.get("data");
                }*/
                imagePackage.uri = cameraImageUri;
                imagePackage.byteArray = readStream(contentResolver.openInputStream(Uri.parse(cameraImageUri.toString())));
                imagePackage.status = true;
            } catch (Exception e){
                e.printStackTrace();
            }
        }
		if(imageSelectedListener != null){
			imageSelectedListener.onImageSelected(imagePackage);
		}
	}
	
	public void setOnImageSelectedListener(OnImageSelectedListener imageSelectedListener) {
		this.imageSelectedListener = imageSelectedListener;
	}

	public interface OnImageSelectedListener{
		public void onImageSelected(ImagePackage imagePackage);
	}
	
    private byte[] readStream ( InputStream inStream ) throws Exception{
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1)
        {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
    
    public class ImagePackage{
    	private boolean status = false;
    	private int type;
    	private Uri uri;
    	private Bitmap bitmap;
    	private byte[] byteArray;
    	
		public boolean status() {
			return status;
		}
		public int getType() {
			return type;
		}
		public Uri getUri() {
			return uri;
		}
		/**
		 * 注意：如果是相册文件，则会压缩成256x256的小图片，但是不影响getByteArray()方法得到的字节数组，
		 * 所以如果要得到无损的图片，请使用getByteArray()。
		 * <p>照相所得图片文件不会进行压缩。</p>
		 * @return
		 */
		public Bitmap getBitmap() {
			if(bitmap == null && byteArray != null){
				BitmapFactory.Options opts = new BitmapFactory.Options();  
	            //开始读入图片，此时把options.inJustDecodeBounds 设回true了  
	        	opts.inJustDecodeBounds = true;  
	    	    BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, opts);
	    	    opts.inJustDecodeBounds = false;
	            int w = opts.outWidth;  
	            int h = opts.outHeight;
	            int scale = 256;
	            //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可  
	            int be = 1;//be=1表示不缩放  
	            if (w > h && w > scale) {//如果宽度大的话根据宽度固定大小缩放  
	                be = (int) (opts.outWidth / scale);  
	            } else if (w < h && h > scale) {//如果高度高的话根据宽度固定大小缩放  
	                be = (int) (opts.outHeight / scale);  
	            }  
	            if (be <= 0)
	                be = 1;  
	            opts.inSampleSize = be;//设置缩放比例  
	            bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, opts);
			}
			return bitmap;
		}
		public byte[] getByteArray() {
			if(byteArray == null && bitmap != null){
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 100, baos);
				byteArray = baos.toByteArray();
				try {
					baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return byteArray;
		}
		public void recycle(){
			uri = null;
			if(bitmap != null){
				bitmap.recycle();
				bitmap = null;
			}
			byteArray = null;
		}
    }
    
    public void setMode(Mode mode){
    	this.mode = mode;
    }
    
    public static enum Mode{
    	/**
    	 * 仅拍照
    	 */
    	CAMERA,
    	/**
    	 * 仅相册
    	 */
    	PHOTO,
    	/**
    	 * 拍照和相册
    	 */
    	CAMERA_AND_PHOTO
    }
}
